package com.itheima.admin.controller;

import com.itheima.admin.pojo.AdUser;
import com.itheima.admin.service.AdUserService;
import com.itheima.common.pojo.Result;
import com.itheima.common.utils.Md5Util;
import com.itheima.common.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/admin")
public class LoginController {

    @Autowired
    private AdUserService adUserService;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result register(@RequestBody AdUser adUser){
        //生成盐
        String salt = RandomUtil.random(10);
        //密码加密
        String password = Md5Util.toMD5(adUser.getPassword(),salt);
        adUser.setPassword(password);
        adUser.setSalt(salt);
        adUser.setId(null);
        boolean flag = adUserService.save(adUser);
        if (!flag){
            return Result.errorMessage("用户已存在");
        }
        return Result.ok();
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result login(@RequestBody AdUser adUser){
        //调用业务层判断用户账号密码是否正确
        String token = adUserService.login(adUser);
        if (token == null){
            return Result.errorMessage("账号或者密码错误");
        }
        return Result.ok(token);
    }

}
